/***
 * Author: Andrey Zhmaylik
 * 		   Erez Bar 
 * 
 * This activity is the main screen that
 * provides client login into server. 
 */


package house.keepper;

import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Connection extends Activity 
{
	private Button m_connect;
	public Socket m_connectionSocket;
	public static DataOutputStream s_out;
	public static ObjectInputStream s_in;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_connect = (Button)findViewById(R.id.connectBtn);
        m_connect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	OpenConnection();
            }               
        });
    }
    
    /***
     * Opens connection with server
     */
    private void OpenConnection()
    {
    	try
    	{
    		int p_num = Integer.parseInt(((EditText)findViewById(R.id.portNum)).getText().toString());
    		EditText et = (EditText)findViewById(R.id.ip_text);
        	String ip =  et.getText().toString();
        	if(this.m_connectionSocket == null)
        	{
        		//Creates socket connection and initializes dataStream objects
        		this.m_connectionSocket = new Socket(ip, p_num);
        		s_out = new DataOutputStream(this.m_connectionSocket.getOutputStream());
        		s_in = new ObjectInputStream(this.m_connectionSocket.getInputStream());
        	}
	        Intent i = new Intent(this, MainScreen.class);
	        startActivity(i);


    	}
    	catch (Exception e) {
    		//If could not create server connection
    		TextView tv = new TextView(this); 
    		tv.setText("Invalid port or ip, press Back");
    		tv.setTextSize(20);
    		android.app.Dialog alertWindow = new android.app.Dialog(this);
    		alertWindow.setTitle("Error");
    		alertWindow.setContentView(tv);
    		alertWindow.show();
		}
    	
    }
}